package com.isoft.illustrationsdraw.config;

import java.net.URI;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.isoft.illustrationsdraw.service.JWTService;

@Component
public class TokenHandshakeInterceptor implements HandshakeInterceptor {

    @Autowired
    private JWTService jwtService;

    @Override
    public boolean beforeHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, 
                                    @NonNull WebSocketHandler wsHandler, @NonNull Map<String, Object> attributes) throws Exception {
        // 获取请求 URI
        URI uri = request.getURI();

        // 从查询参数中提取 token
        String query = uri.getQuery();
        if (query == null || !query.contains("token=")) {
            response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return false;
        }

        // 提取 token 的值
        String token = null;
        for (String param : query.split("&")) {
            if (param.startsWith("token=")) {
                token = param.substring("token=".length());
                break;
            }
        }

        if (token == null || !jwtService.validateToken(token)) {
            response.setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return false;
        }

        // 将 Token 存储到 attributes 中，供后续使用
        attributes.put("token", token);
        return true;
    }

    @Override
    public void afterHandshake(@NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response, 
                               @NonNull WebSocketHandler wsHandler, @Nullable Exception exception) {
        // 握手成功后的操作（如需要）
    }
}
